package com.bs.service;

import java.net.MalformedURLException;
import java.rmi.RemoteException;

import javax.xml.namespace.QName;
import javax.xml.rpc.ServiceException;

import com.bs.web.rest.LogAlertResource;

import org.apache.axis.client.Call;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class MsgConfigService {
    @Value("${msgConfig.authEndPoint}")
    private String authEndPoint;
    @Value("${msgConfig.sendEndPoint}")
    private String sendEndPoint;
    @Value("${msgConfig.userName}")
    private String userName;
    @Value("${msgConfig.password}")
    private String password;
    @Value("${msgConfig.ipAddress}")
    private String ipAddress;


	public boolean sendMessage(String[] phones, String message) {
        try {
//            String authEndPoint = "http://10.251.20.27:9080/bsms/services/BsmsAuthentication";
//            String sendEndPoint = "http://10.251.20.27:9080/bsms/services/BsmsSendProxy";
            Call loginCall = createCall(authEndPoint, "loginWithIpAddress");
            String identity = (String) loginCall.invoke(composeLoginArgs(
                    userName, password, ipAddress));
            Call sendMessageCall = createCall(sendEndPoint, "sendMessage");
            sendMessageCall.invoke(composeSendMessageArgs(
                    phones, message, identity));
            return true;
        } catch (ServiceException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        return false;
    }

	private Call createCall(String endPoint, String methodName)
			throws ServiceException, MalformedURLException {
        org.apache.axis.client.Service service = new  org.apache.axis.client.Service();
		Call call = (Call) service.createCall();
		call.setOperationName(new QName(endPoint, methodName));
		call.setTargetEndpointAddress(new java.net.URL(endPoint));
		return call;
	}

	private Object[] composeLoginArgs(String userName, String password,
			String ipAddress) {
		return new Object[] { userName, password, ipAddress };
	}

	private Object[] composeSendMessageArgs(String[] phoneNumbers,
			String message, String identity) {
		return new Object[] { phoneNumbers, message, 2, 2, identity };
	}
}
